<template>
  <el-form v-show="getShow" ref="smsLoginRef" :model="smsLoginForm" :rules="smsLoginRules">
    <el-form-item v-if="tenantEnabled" prop="tenantId">
      <el-select v-model="smsLoginForm.tenantId" filterable :placeholder="proxy.$t('sms.selectPlaceholder')" style="width: 100%">
        <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
        <template #prefix>
          <svg-icon icon-class="company" class="el-input__icon input-icon" />
        </template>
      </el-select>
    </el-form-item>
    <el-form-item prop="phonenumber">
      <el-input v-model="smsLoginForm.phonenumber" type="text" size="large" auto-complete="off" :placeholder="proxy.$t('sms.phoneNumber')">
        <template #prefix>
          <svg-icon icon-class="phone" class="el-input__icon input-icon" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="smsCode">
      <el-input v-model="smsLoginForm.smsCode" prefix-icon="CircleCheck" :placeholder="proxy.$t('sms.smsCode')">
        <template #append>
          <span v-if="mobileCodeTimer <= 0" :title="proxy.$t('sms.GetSmsCode')" @click="sendSmsCode">{{ proxy.$t('sms.GetSmsCode') }}</span>
          <span v-else>{{ mobileCodeTimer }}{{ proxy.$t('sms.ReGetSmsCode') }}</span>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
        <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
        <span v-else>{{ proxy.$t('login.logging') }}</span>
      </el-button>
    </el-form-item>
    <div style="padding: 0px 0px 20px 0px">
      <el-button plain size="large" style="width: 100%" @click="handleBack">
        <span>{{ proxy.$t('login.back') }}</span>
      </el-button>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { getTenantList } from '@/api/login';
import { LoginStateEnum, useLoginState } from './loginState';
import { useUserStore } from '@/store/modules/user';
import { smsCode } from '@/api/system/sms';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const mobileCodeTimer = ref(0);
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const { getLoginState, handleBackLogin } = useLoginState();
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE);

const redirect = ref(undefined);
const smsLoginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);
// 租户开关
const tenantEnabled = ref(true);
const loading = ref(false);

const smsLoginForm = ref<LoginData>({
  tenantId: '000000',
  phonenumber: '',
  smsCode: '',
  grantType: 'sms',
  uuid: ''
} as LoginData);

const smsLoginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('sms.rule.tenantId.required') }],
  phonenumber: [{ required: true, trigger: 'blur', message: t('sms.rule.phonenumber.required') }],
  smsCode: [{ required: true, trigger: 'change', message: t('sms.rule.smsCode.required') }]
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      smsLoginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

const sendSmsCode = async () => {
  smsLoginRef.value?.validateField('phonenumber', async (valid: boolean) => {
    if (valid) {
      let phonenumber = smsLoginForm.value.phonenumber;
      await smsCode(phonenumber as string).then(async () => {
        ElMessage.success(t('sms.sendSmsCodeSuccess'));
        // 设置倒计时
        mobileCodeTimer.value = 60;
        let msgTimer = setInterval(() => {
          mobileCodeTimer.value = mobileCodeTimer.value - 1;
          if (mobileCodeTimer.value <= 0) {
            clearInterval(msgTimer);
          }
        }, 1000);
      });
    }
  });
};

const handleLogin = () => {
  smsLoginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 调用action的登录方法
      const [err] = await to(userStore.login(smsLoginForm.value));
      if (!err) {
        await router.push({ path: redirect.value || '/' });
        loading.value = false;
      } else {
        loading.value = false;
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

const handleBack = () => {
  handleBackLogin();
  smsLoginRef.value?.clearValidate();
};

onMounted(() => {
  initTenantList();
});
</script>
